/*
 * Copyright 2009 Cedric Priscal
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android_serialport_api;

import android.util.Log;

import com.ytd.common.util.LogUtil;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class SerialPort {
    private static final String TAG = "SerialPort";

    static {
        try {
            System.loadLibrary("SerialPort");
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }

    boolean mOpened = false;
    SerialCallback mCallback;
    StringBuilder buffer = new StringBuilder();
    //打开串口
    private FileDescriptor mFd;  //Do not remove or rename the field mFd: it is used by native method close();
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;
    private ReadThread mThread;

    /**
     * 默认方式 （Callback）
     * 为了兼容以前代码
     *
     * @param device
     * @param baudrate
     * @param Callback
     * @throws SecurityException
     * @throws IOException
     */
    public SerialPort(File device, int baudrate, SerialCallback Callback) throws SecurityException, IOException {
        if (!device.canRead() || !device.canWrite()) {
            try {
                Process su = Runtime.getRuntime().exec("/system/bin/su");
                String cmd = "chmod 666 " + device.getAbsolutePath() + "\nexit\n";
                su.getOutputStream().write(cmd.getBytes());
                if (su.waitFor() != 0 || !device.canRead() || !device.canWrite()) {
                    throw new SecurityException();
                }
            } catch (Exception var6) {
                var6.printStackTrace();
                throw new SecurityException();
            }
        }
        mFd = open(device.getAbsolutePath(), baudrate, 0);
        if (mFd == null) {
            Log.e(TAG, "native open returns null");
            throw new IOException();
        }
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
        mCallback = Callback;
        mOpened = true;
        mThread = new ReadThread();
        mThread.start();
    }

    /**
     * 标准写法
     *
     * @param device 设备
     * @param baudrate 比特率
     * @throws SecurityException
     * @throws IOException
     */
    public SerialPort(File device, int baudrate) throws SecurityException, IOException {
        if (!device.canRead() || !device.canWrite()) {
            try {
                Process su = Runtime.getRuntime().exec("/system/bin/su");
                String cmd = "chmod 666 " + device.getAbsolutePath() + "\nexit\n";
                su.getOutputStream().write(cmd.getBytes());
                if (su.waitFor() != 0 || !device.canRead() || !device.canWrite()) {
                    throw new SecurityException();
                }
            } catch (Exception var6) {
                var6.printStackTrace();
                throw new SecurityException();
            }
        }
        mFd = open(device.getAbsolutePath(), baudrate, 0);
        if (mFd == null) {
            Log.e(TAG, "native open returns null");
            throw new IOException();
        }
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }


    //JNI
    private static native FileDescriptor open(String path, int baudrate, int flags);

    public native void close();

    public boolean send(byte[] data) {
        if (data != null) {
            return send(data, 0, data.length);
        } else {
            return false;
        }
    }

    public boolean send(byte[] data, int offset, int len) {
        if (mFileOutputStream != null) {
            try {
                final int max = 15;
                int cnt = max;
                while (len > 0) {
                    cnt = Math.min(max, len);
                    mFileOutputStream.write(data, offset, cnt);
                    mFileOutputStream.flush();
                    len -= cnt;
                    offset += cnt;
                }
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return false;
    }

    public void tcflush() {
    }

    public void closePort() {
        try {
            mOpened = false;
            if (mFileInputStream != null) {
                mFileInputStream.close();
            }
            if (mFileOutputStream != null) {
                mFileOutputStream.close();
            }
            if (mCallback != null) {
                mCallback = null;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        close();
    }

    // Getters and setters
    public InputStream getInputStream() {
        return mFileInputStream;
    }

    public OutputStream getOutputStream() {
        return mFileOutputStream;
    }

    private class ReadThread extends Thread {

        @Override
        public void run() {
            super.run();
            byte[] mReadBuffer = new byte[1];
            while (mOpened) {
                try {
                    if (mFileInputStream == null) {
                        return;
                    }
                    int available = mFileInputStream.available();
                    if (available > 0) {
                        mFileInputStream.read(mReadBuffer);
                        buffer.append(new String(mReadBuffer));
                        if (mReadBuffer[0] == 0x0a || mReadBuffer[0] == 0x0D) {
                            if (mCallback != null) {
                                mCallback.onReadData(buffer.toString());
                            }
                            buffer.setLength(0);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtil.e("ReadThread Exception", e);
                }
            }
        }
    }
}
